package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component  //注意：不要漏掉该注解，否则请求不会到这个类中，
public class AuthorizeFilter implements GlobalFilter, Ordered {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//1、获取请求对象
		ServerHttpRequest request = exchange.getRequest();
		//2、获取相应对象，（就是用来返回错误信息）
		ServerHttpResponse response = exchange.getResponse();
		//3、获取请求路径path，判断是不是登录路径，若是，放行；不是，则获取请求头headers
		String path = request.getURI().getPath();
		if (path.contains("/admin/login")){
			return chain.filter(exchange);
		}

		//4、获取请求头
		HttpHeaders headers = request.getHeaders();
		String jwtToken = headers.getFirst("token");

		//5、判断请求头中的token对象的value是否为空，为空，则返回错误信息；不为空，判断jwt是否合法
		if (StringUtils.isEmpty(jwtToken)){
			response.setStatusCode(HttpStatus.UNAUTHORIZED);
			//封装response并返回
			return response.setComplete();
		}

		//6、使用try catch,解析jwt令牌，若不合法，返回错误信息，合法，则放行
		try {
			JwtUtil.parseJWT(jwtToken);
		} catch (Exception e) {
			e.printStackTrace();//注意：该句应该放在return前面
			response.setStatusCode(HttpStatus.UNAUTHORIZED);
			//封装response并返回
			return response.setComplete();
		}

		return chain.filter(exchange);//注意：这里不能返回null，否则永远访问不了服务，即永远报401：没权限
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
